<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Doctrine resource class for Zend_Application
 *
 * @category    RedCross
 * @package     RedCross_Application
 */
class RedCross_Application_Resource_Doctrine extends Zend_Application_Resource_ResourceAbstract
{

    public function init()
    {
        $doctrineConfig = $this->getOptions();

//        require_once 'Doctrine/Core.php';
        require_once 'Doctrine.compiled.php';

        $this->getBootstrap()->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine_Core', 'autoload'), 'Doctrine');

        $manager = Doctrine_Manager::getInstance();

        // set models to be autoloaded and not included (Doctrine_Core::MODEL_LOADING_AGGRESSIVE)
        $manager->setAttribute(
            Doctrine_Core::ATTR_MODEL_LOADING,
            Doctrine_Core::MODEL_LOADING_CONSERVATIVE
        );

        $manager->setAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT, $doctrineConfig['table_name_format']);

        // enable validation on save()
        $manager->setAttribute(
            Doctrine_Core::ATTR_VALIDATE,
            Doctrine_Core::VALIDATE_ALL
        );

        // enable sql callbacks to make SoftDelete and other behaviours work transparently
        $manager->setAttribute(
            Doctrine_Core::ATTR_USE_DQL_CALLBACKS,
            true
        );

        // enable automatic queries resource freeing
        $manager->setAttribute(
            Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS,
            true
        );

        // connect to database
        $manager->openConnection($doctrineConfig['connection_string']);

        // set to utf8
        $manager->connection()->setCharset('utf8');

        if (isset($doctrineConfig['cache']) && $doctrineConfig['cache'] == true)
        {
            $cacheDriver = new Doctrine_Cache_Apc();

            $manager->setAttribute(Doctrine_Core::ATTR_QUERY_CACHE, $cacheDriver);
            $manager->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE, $cacheDriver);
            // Global result cache lifespan of 1 hour
            $manager->setAttribute(Doctrine_Core::ATTR_RESULT_CACHE_LIFESPAN, 3600);
        }

        return $manager;
    }
}